<template>
  <el-dropdown trigger="click" class="ml8">
        <el-button :loading="exportLoading" size="medium" type="success">数据导出<i class="el-icon-arrow-down el-icon--right"/></el-button>
        <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="exportExcel(1)">导出查询结果</el-dropdown-item>
            <el-dropdown-item @click.native="exportExcel(2)">导出全部数据</el-dropdown-item>
        </el-dropdown-menu>
    </el-dropdown>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
    name:"exportExcel",
    props:{
        apiFn:{
            default: () => (()=>{}),
            type: Function,
            required: true
        },
        options:{
            default:()=>({}),
            type: Object,
        },
        dataFn:{
            default: function(){},
            type: Function
        },
        self:{
            default: false,
            type: Boolean
        },
        name:{
            default: new Date().getTime()
        },
    },

    data(){
        return{
            exportLoading: false
        }
    },
    methods:{
        exportExcel(i){
            this.exportLoading = true
            let options = {allPage:2,...this.options}
            if(i === 1){
                const ops = this.$parent.$parent.pageparm
                options = {...options,...ops,page:null,perPage:null}
            }
            const headerList =this.$parent.$parent.headerList
            const tableHeadeInfo = headerList.reduce((obj,item)=>{
                if(item.exportName){
                    obj[item.exportName] = item.label
                }else{
                    obj[item.prop] = item.label
                }
                return obj
            },{})
            // console.log(tableHeadeInfo)
            const tableHeade= Object.keys(tableHeadeInfo)
            
            let thead = '<thead><tr>'
            for(let key in tableHeadeInfo){
                thead +=  `<td>${tableHeadeInfo[key]}</td>`
            }
            thead += '</tr></thead>'

            let tbody = '<tbody>'
            let tabStr = "";
            this.apiFn(options).then(({data}) =>{
                if(this.self){
                    tabStr = this.dataFn(data,tableHeade)
                }else{
                    data.forEach((item, index) => {
                        let tabRowStr = "";
                        tabStr += `<tr>`;
                        for (let i = 0; i < tableHeade.length; i++ ) {
                            const key = tableHeade[i]
                            if (/\./g.test(key)) {
                                let arr = key.split('.')
                                tabRowStr += `<td>${item[arr[0]] ? item[arr[0]][arr[1]] : ''}</td>`;
                            } else {
                                tabRowStr += `<td>${item[key] || ''}</td>`;
                            }
                        }
                        tabStr += tabRowStr;
                        tabStr += "</tr>";
                    });
                }
                tbody += tabStr;
                tbody += '</tbody>'
                let tableStr = thead + tbody
                let table = document.createElement("table")
                table.innerHTML = tableStr
                let xlsxParam = { raw: true };
                let wb = XLSX.utils.table_to_book(table,xlsxParam)
                /* 获取二进制字符串作为输出 */
                let wbout = XLSX.write(wb, {
                    bookType: "xlsx",
                    bookSST: false,
                    type: "array"
                });
                try {
                    FileSaver.saveAs(
                        new Blob([wbout], { type: "application/octet-stream" }),
                        //设置导出文件名称
                        `${this.name}.xlsx`
                    );
                } catch (e) {
                    if (typeof console !== "undefined") console.log(e, wbout);
                }
                this.exportLoading = false
                return wbout;

            }).catch(()=>{
                this.exportLoading = false
                this.$message.error('导出失败!')
            })
        },

    }
}
</script>

<style>

</style>